package com.android.stockme.backend;

import com.android.stockme.backend.configuration.IConfigurationChangedListener;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public class Timer extends Thread implements IConfigurationChangedListener {

	private Timer instance = null;
	
	private Handler handler = null;
	private IBackendMessageQueue messageQueue = null;
	private String title = null;
	private IASyncComputation task = null;
	private int interval = 0;

	private boolean isScheduling = false;
	private boolean taskScheduled = false;
	
	public Timer(IBackendMessageQueue messageQueue, String title, IASyncComputation task, int interval) {
		this.messageQueue = messageQueue;
		this.title = title;
		this.task = task;
		this.interval = interval;
		this.setName(this.title);
	
		this.instance = this;		
	}
	
	@Override
	public void run() {
		Looper.prepare();
		this.handler = new Handler();
		Looper.loop();
	}

	public void notifyConfigurationChanged(Object arg) {
		this.interval = (Integer)arg;
	}
	
	public synchronized void startScheduling() {
		this.isScheduling = true;
		if (this.taskScheduled == false) {
			Log.d("StockMe", title + " scheduling");
			this.schedule();
			this.taskScheduled = true;
		}
	}
	
	public synchronized void stopScheduling() {
		this.isScheduling = false;
	}
	
	public synchronized boolean isScheduling() {
		return this.isScheduling;
	}
	
	private void schedule() {
		this.handler.postDelayed(new Runnable() {
			public void run() {
				synchronized (instance) {
					if (isScheduling) {
						Log.d("StockMe", title + " computing");
						task.compute();
						Log.d("StockMe", title + " posting");
						taskScheduled = false;
						messageQueue.post(task);
						//Log.d("StockMe", title + " scheduling");
						//schedule();
						//taskScheduled = true;
						Log.d("StockMe", title + " exiting");															
					}
					else {
						taskScheduled = false;
						Log.d("StockMe", title + " skipped scheduling");
					}
				}
			}
		}, this.interval * 1000);		
	}
}
